"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getTags = exports.searchNotes = exports.deleteNote = exports.updateNote = exports.createNote = exports.getNoteById = exports.getNotes = void 0;
const Note_1 = require("../models/Note");
const getNotes = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
    var _a;
    try {
        const userId = (_a = req.user) === null || _a === void 0 ? void 0 : _a.id;
        const { page = 1, limit = 10, search, tags } = req.query;
        const query = { userId };
        // 搜索功能
        if (search) {
            query.$or = [
                { title: { $regex: search, $options: 'i' } },
                { content: { $regex: search, $options: 'i' } }
            ];
        }
        // 标签筛选
        if (tags) {
            const tagArray = Array.isArray(tags) ? tags : [tags];
            query.tags = { $in: tagArray };
        }
        const pageNum = parseInt(page);
        const limitNum = parseInt(limit);
        const skip = (pageNum - 1) * limitNum;
        const notes = yield Note_1.Note.find(query)
            .sort({ updatedAt: -1 })
            .skip(skip)
            .limit(limitNum);
        const total = yield Note_1.Note.countDocuments(query);
        res.json({
            success: true,
            data: {
                notes,
                pagination: {
                    page: pageNum,
                    limit: limitNum,
                    total,
                    pages: Math.ceil(total / limitNum)
                }
            }
        });
    }
    catch (error) {
        res.status(500).json({
            success: false,
            message: '获取笔记列表失败',
            error: error.message
        });
    }
});
exports.getNotes = getNotes;
const getNoteById = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
    var _a;
    try {
        const { id } = req.params;
        const userId = (_a = req.user) === null || _a === void 0 ? void 0 : _a.id;
        const note = yield Note_1.Note.findOne({ _id: id, userId });
        if (!note) {
            res.status(404).json({
                success: false,
                message: '笔记不存在'
            });
            return;
        }
        res.json({
            success: true,
            data: { note }
        });
    }
    catch (error) {
        res.status(500).json({
            success: false,
            message: '获取笔记失败',
            error: error.message
        });
    }
});
exports.getNoteById = getNoteById;
const createNote = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
    var _a;
    try {
        const { title, content, tags, isPublic } = req.body;
        const userId = (_a = req.user) === null || _a === void 0 ? void 0 : _a.id;
        const note = new Note_1.Note({
            userId,
            title,
            content,
            tags: tags || [],
            isPublic: isPublic || false
        });
        yield note.save();
        res.status(201).json({
            success: true,
            message: '笔记创建成功',
            data: { note }
        });
    }
    catch (error) {
        res.status(500).json({
            success: false,
            message: '创建笔记失败',
            error: error.message
        });
    }
});
exports.createNote = createNote;
const updateNote = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
    var _a;
    try {
        const { id } = req.params;
        const { title, content, tags, isPublic } = req.body;
        const userId = (_a = req.user) === null || _a === void 0 ? void 0 : _a.id;
        const note = yield Note_1.Note.findOneAndUpdate({ _id: id, userId }, {
            title,
            content,
            tags: tags || [],
            isPublic: isPublic || false,
            updatedAt: new Date()
        }, { new: true, runValidators: true });
        if (!note) {
            res.status(404).json({
                success: false,
                message: '笔记不存在'
            });
            return;
        }
        res.json({
            success: true,
            message: '笔记更新成功',
            data: { note }
        });
    }
    catch (error) {
        res.status(500).json({
            success: false,
            message: '更新笔记失败',
            error: error.message
        });
    }
});
exports.updateNote = updateNote;
const deleteNote = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
    var _a;
    try {
        const { id } = req.params;
        const userId = (_a = req.user) === null || _a === void 0 ? void 0 : _a.id;
        const note = yield Note_1.Note.findOneAndDelete({ _id: id, userId });
        if (!note) {
            res.status(404).json({
                success: false,
                message: '笔记不存在'
            });
            return;
        }
        res.json({
            success: true,
            message: '笔记删除成功'
        });
    }
    catch (error) {
        res.status(500).json({
            success: false,
            message: '删除笔记失败',
            error: error.message
        });
    }
});
exports.deleteNote = deleteNote;
const searchNotes = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
    var _a;
    try {
        const userId = (_a = req.user) === null || _a === void 0 ? void 0 : _a.id;
        const { q } = req.query;
        if (!q) {
            res.status(400).json({
                success: false,
                message: '搜索关键词不能为空'
            });
            return;
        }
        const notes = yield Note_1.Note.find({
            userId,
            $or: [
                { title: { $regex: q, $options: 'i' } },
                { content: { $regex: q, $options: 'i' } },
                { tags: { $regex: q, $options: 'i' } }
            ]
        }).sort({ updatedAt: -1 });
        res.json({
            success: true,
            data: { notes }
        });
    }
    catch (error) {
        res.status(500).json({
            success: false,
            message: '搜索笔记失败',
            error: error.message
        });
    }
});
exports.searchNotes = searchNotes;
const getTags = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
    var _a;
    try {
        const userId = (_a = req.user) === null || _a === void 0 ? void 0 : _a.id;
        const tags = yield Note_1.Note.aggregate([
            { $match: { userId } },
            { $unwind: '$tags' },
            { $group: { _id: '$tags', count: { $sum: 1 } } },
            { $sort: { count: -1 } }
        ]);
        res.json({
            success: true,
            data: { tags: tags.map(tag => ({ name: tag._id, count: tag.count })) }
        });
    }
    catch (error) {
        res.status(500).json({
            success: false,
            message: '获取标签失败',
            error: error.message
        });
    }
});
exports.getTags = getTags;
